package team.scau.laboratory_repair.common.exception.handler;

import lombok.extern.apachecommons.CommonsLog;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import team.scau.laboratory_repair.common.exception.DataGridException;
import team.scau.laboratory_repair.common.json.JqGridResult;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

/**
 * @Description:全局异常处理，可以在这里定义自己的异常
 * @Author:ZTF
 * @Date:2018/5/22 17:28
 */
@ControllerAdvice
@CommonsLog
public class GlobalExceptionHandler {
    public static final String DEFAULT_ERROR_VIEW = "error";
    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        log.warn("***********发生未知异常**********");
        log.error(e.getMessage(), e);
        log.warn("异常栈:");
        for (StackTraceElement s :e.getStackTrace()) {
            log.error("\tat " + s);
        }
        mav.addObject("message", e.getMessage());
        mav.addObject("error", e.getClass().getName());
        mav.addObject("status", "500");
        mav.addObject("timestamp", new Date());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }

    @ExceptionHandler(value = DataGridException.class)
    @ResponseBody
    public JqGridResult dataGridException(HttpServletRequest req, Exception e){
        log.warn("***********发生未知异常**********");
        log.warn("异常栈:"+ Arrays.toString(e.getStackTrace()));
        log.warn("异常url:+"+e.getMessage());
        return new JqGridResult();
    }

}
